<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 500px;
        height: 600px;
        border: 1px solid #000;
        overflow: auto;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <input type="text" />
    <button>btn</button>

    <script>
      const name = prompt("请输入姓名");
      // 将时间戳作为每个人的唯一的id
      const id = new Date().getTime();
      const box = document.querySelector(".box");
      const input = document.querySelector("input");
      const button = document.querySelector("button");

      // 创建一个前端的websocket实例
      // 传入一个要连接的后端地址
      const ws = new WebSocket("ws://10.31.159.91:8080");

      // 打开连接的回调
      ws.onopen = function (evt) {
        console.log("Connection open ...");
        // 前端向后端发送
        // ws.send("Hello WebSockets!");
      };

      // 监听到后端发来内容的回调
      ws.onmessage = function (evt) {
        // console.log("Received Message: " + evt.data);
        // 手动关闭连接
        // ws.close();

        const obj = JSON.parse(evt.data);

        box.innerHTML += `<p style="text-align: ${
          obj.id === id ? "right" : "left"
        }">${obj.name}说：${obj.value}</p>`;
      };

      // 监听连接断开的回调
      ws.onclose = function (evt) {
        console.log("Connection closed.");
      };

      button.onclick = () => {
        // 在使用websocket发送信息的时候，只能发送字符串
        ws.send(
          JSON.stringify({
            id,
            name,
            value: input.value,
          })
        );
        input.value = "";
      };
    </script>
  </body>
</html>
